import type { MicroAppData, MicroAppInitState, MicroAppMessage } from './types';

/**
 * 微应用状态管理器（React 场景专用，内存单例）
 */
class MicroAppManager {
  private static instance: MicroAppManager;
  private state?: MicroAppInitState;
  private constructor() {}
  /** 获取全局唯一单例 */
  public static getInstance(): MicroAppManager {
    if (!this.instance) this.instance = new MicroAppManager();
    return this.instance;
  }
  /** 获取当前状态 */
  public getState(): MicroAppInitState | undefined {
    return this.state;
  }
  /** 设置状态 */
  public setState(data: MicroAppInitState): void {
    this.state = data;
  }
  /** 处理消息事件（如 postMessage） */
  public handleMessage(event: MessageEvent): void {
    try {
      const { type, data } = event.data as MicroAppMessage;
      if (type === 'MICRO_APP_INIT_DATA') {
        this.setState({ initialized: true, initTime: Date.now(), data });
      }
    } catch {}
  }
}

export const getMicroAppManager = (): MicroAppManager => MicroAppManager.getInstance();

export function defaultHandleMessage(event: MessageEvent) {
  getMicroAppManager().handleMessage(event);
} 